﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utility
{
    public class ClientInfo
    {
        public ClientStatus Status;
        public string UserName;
    }

    public class ClientList : BaseMessage
    {
        public List<ClientInfo> Clients;

        public ClientList()
        {
            Clients = new List<ClientInfo>();
        }

        public ClientList(IEnumerable<ClientComputer> cls)
        {
            Clients = cls.Select(cl => new ClientInfo
                {
                    UserName = cl.UserName,
                    Status = cl.Status == ClientStatus.Free ? ClientStatus.Free : ClientStatus.Playing
                }).Distinct().ToList();
        }

        public ClientList(byte[] data)
        {
            Clients = new List<ClientInfo>();
            int offset = 0;
            int n = BitConverter.ToInt32(data, offset);
            offset += 4;
            for (int i = 0; i < n; i++)
            {
                var client = new ClientInfo();
                client.Status = (ClientStatus) BitConverter.ToInt32(data, offset);
                offset += 4;
                int nameSize = BitConverter.ToInt32(data, offset);
                offset += 4;
                client.UserName = Encoding.UTF8.GetString(data, offset, nameSize);
                offset += nameSize;
                Clients.Add(client);
            }
        }

        public ClientList(string s)
            : this(Encoding.UTF8.GetBytes(s))
        {
        }

        public ClientInfo this[int index]
        {
            get
            {
                try
                {
                    return Clients[index];
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }

        public override byte[] ToByteArray()
        {
            var bytes = new List<byte>();
            bytes.AddRange(BitConverter.GetBytes(Clients.Count));
            foreach (ClientInfo client in Clients)
            {
                bytes.AddRange(BitConverter.GetBytes((int) client.Status));
                bytes.AddRange(BitConverter.GetBytes(client.UserName.Length));
                bytes.AddRange(Encoding.UTF8.GetBytes(client.UserName));
            }
            return bytes.ToArray();
        }
    }
}